local gamelib = require "club.threecard.gamelib"
local slotlib = require "club.threecard.slotlib"
local components = slotlib.require "components"

local slot_system = slotlib.systems.slot_system
local class = gamelib.entitas.class
local Matcher = gamelib.entitas.Matcher
local GroupEvent = gamelib.entitas.GroupEvent

local stop_machine_system = class("stop_machine_system", slot_system)

function stop_machine_system:initialize()
    self.context.machine:replace(components.reel_offset_component, {})
end

function stop_machine_system:get_trigger()
    return {{Matcher({components.reel_offset_component}), GroupEvent.ADDED}};
end

function stop_machine_system:filter(entity)
    return entity:has(components.reel_offset_component)
end

function stop_machine_system:cleanup()
    self._entities:clear()
end

function stop_machine_system:execute(entitas)
    if entitas:size() ~= 1 then
        gamelib.log.error("数据错误，结果组件不可能>1")
        return;
    end

    local finished = false;
    entitas:foreach(function(e)
        local offsets = e:get(components.reel_offset_component).reel_offsets;
        local over_handler = function()
            finished = true;
        end
        self.ingame.machine:stop(offsets, over_handler);
    end)

    while not finished do
        self:step();
    end
end

function stop_machine_system:skip()
    self.super.skip(self);
    self.ingame.machine:stop_immediate();
end

return stop_machine_system